<template>
  <div class="system-role-container layout-padding">
    <TableForm
      v-model:loading="loading"
      :columns="columns"
      :form-columns="formColumns"
      :data="list"
      :total="tableTotal"
      :pagination="pagination"
      row-key="name"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren', defaultExpandAll: true }"
      @open-form="onOpenForm"
      @fetch="onFetch"
      @input="onInput"
    >
      <template v-slot:column>
        <el-table-column
          v-for="(column, index) in columns"
          :key="index"
          :type="column.type"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :show-overflow-tooltip="column.showOverflowTooltip"
        >
          <template v-if="['title', 'path', 'id'].includes(column.prop || '')" #default="{ row }">
            <span v-html="row[String(column.prop)]" />
          </template>

          <template v-else-if="column.prop === 'isHide'" #default="{ row }">
            <el-tag v-if="row.meta.isHide" type="danger">隐藏</el-tag>
          </template>

          <!--        <template v-else-if="column.prop === 'cat'" #default="{ row }">-->
          <!--          <el-tag v-if="row.cat === 0" :type="row['cat'] ? 'success' : 'primary'" size="small">-->
          <!--            {{ row.actions.length }}-->
          <!--          </el-tag>-->
          <!--        </template>-->

          <template v-else-if="column.prop === 'action'" #default="{ row }">
            <el-button size="small" text type="success" @click="onOpenAddMenu(row)">新增</el-button>
            <el-button size="small" text type="primary" @click="onOpenEditMenu('edit', row)">
              修改
            </el-button>
            <el-button
              v-if="!row.children.length && !systemKeys.includes(row.id)"
              size="small"
              text
              @click="openPage(row, 'systemCustom', '表格')"
            >
              表格
            </el-button>
            <el-button
              v-if="!row.children.length && !systemKeys.includes(row.id)"
              size="small"
              text
              @click="openPage(row, 'systemQuery', '查询')"
            >
              查询
            </el-button>
            <el-button
              v-if="!row.children.length && !systemKeys.includes(row.id)"
              size="small"
              text
              @click="openPage(row, 'systemForm', '表单')"
            >
              表单
            </el-button>
            <el-button
              v-if="!row['isSys']"
              text
              size="small"
              type="danger"
              @click="onTableRowDel(row)"
              :disabled="row['isSys']"
            >
              删除
            </el-button>

            <!--          :disabled="row['isSys']"-->
          </template>
        </el-table-column>
      </template>
    </TableForm>
    <!--组件-->
    <MenuDialog ref="dialogRef" @refresh="onFetch()" />
  </div>
</template>

<script setup lang="ts" name="systemMenu">
import { ref, defineAsyncComponent, onBeforeMount } from 'vue'
import TableForm from '@/components/TableForm/TableForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useBaseApi } from '@/api/base'
import { useRouter } from 'vue-router'
import type { FormColumn, TableFormColumn, TableFormPagination } from '@/types/custom'
import { useI18n } from 'vue-i18n'
import { debounce, eachTree, searchTree, toValueString } from 'xe-utils'
import { Session } from '@/utils/storage'

// 引入组件
const MenuDialog = defineAsyncComponent(() => import('@/views/system/business/menu/MenuDialog.vue'))

const { GetBusinessTree, DelBusiness } = useBaseApi()
const router = useRouter()
const { t } = useI18n()

// 编辑
const dialogRef = ref()
// 加载
const loading = ref(false)
// 表格数据
const tableData = ref<any[]>([])
// 检索数据
const list = ref<any[]>([])
// 表格总数
const tableTotal = ref(0)
// 筛选列
const formColumns = ref<FormColumn[]>([{ type: 'string', label: '关键字', prop: 'title' }])
// 表格列
const columns = ref<TableFormColumn[]>([
  { type: 'selection', label: '', width: 38 },
  { prop: 'title', label: '菜单名称', minWidth: 150, showOverflowTooltip: true },
  { prop: 'isHide', label: '菜单中', minWidth: 60, showOverflowTooltip: true },
  // {prop: 'component', label: '组件路径', minWidth: 100, showOverflowTooltip: true},
  { prop: 'path', label: '路由路径', minWidth: 100, showOverflowTooltip: true },
  // {prop: 'cat', label: '按钮数量', minWidth: 100, showOverflowTooltip: true},
  { prop: 'idx', label: '排序', minWidth: 50 },
  { prop: 'id', label: 'ID', minWidth: 200, showOverflowTooltip: true },
  { prop: 'action', label: '操作', minWidth: 180 }
])
// 分页
const pagination = ref<TableFormPagination>({
  page: 1,
  pageSize: 10
})
// 系统菜单
const systemKeys = ['sys_business_manager']

/**
 * 初始化表格数据
 */
const onFetch = () => {
  loading.value = true
  return GetBusinessTree()
    .then(({ data }) => {
      // console.log(data)
      tableData.value = data
      const params = Session.get('menu_form_title') || {}
      searchEvent(params.title || undefined)
      return data
    })
    .finally(() => {
      loading.value = false
    })
}

const onInput = debounce((value?: string) => {
  searchEvent(value)
}, 500)

const searchEvent = (value?: string) => {
  const filterVal = toValueString(value || '')
    .trim()
    .toLowerCase()
  if (filterVal) {
    const options = { children: 'children' }
    const searchProps = ['title', 'path', 'id']
    const rest = searchTree(
      tableData.value,
      (item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1),
      options
    )
    // 高亮选中
    const filterRE = new RegExp(filterVal, 'gi')
    eachTree(
      rest,
      (item) => {
        searchProps
          .filter((f) => f === 'title')
          .forEach((key) => {
            item[key] = String(item[key]).replace(
              filterRE,
              (match) => `<span class="color-primary">${match}</span>`
            )
          })
      },
      options
    )
    // 赋值
    list.value = rest
    // // 搜索之后默认展开所有子节点
    // nextTick(() => {
    //   const $table = tableRef.value
    //   if ($table) {
    //     $table.setAllTreeExpand(true)
    //   }
    // })
  } else {
    list.value = tableData.value
  }
}

/**
 * 自定义表格
 * @param row
 * @param name
 * @param title
 */
const openPage = (row: TypedAny, name: string, title: string) => {
  router.push({
    name,
    query: {
      id: row.id,
      tagsViewName: `${t(row.meta.title || '')}-${title}`
    }
  })
}

/**
 * 打开新增菜单弹窗
 * @param row
 */
const onOpenAddMenu = (row?: any) => {
  dialogRef.value.openDialog('add', row ? { pid: row.id, path: row.path } : {})
}

/**
 * 打开编辑菜单弹窗
 * @param type
 * @param row
 */
const onOpenEditMenu = (type: string, row: RouteItem) => {
  dialogRef.value.openDialog(type, row)
}

/**
 * 删除当前行
 * @param row
 */
const onTableRowDel = (row: RouteItem) => {
  const tPath = String(row.meta?.title || row.name)
  ElMessageBox.confirm(`此操作将永久删除路由：《${t(tPath)}》, 是否继续?`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      DelBusiness(row.id).then(() => {
        ElMessage.success('删除成功')
        onFetch()
      })
      // 做刷新菜单一些列操作
      //await setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
    })
    .catch(() => {})
}

/**
 * 打开表单
 * @param type
 * @param row
 */
const onOpenForm = (type: string, row?: any) => {
  dialogRef.value && dialogRef.value.openDialog(type, row)
}

// 页面加载时
onBeforeMount(() => {
  onFetch()
})
</script>
